package cn.jnetty.ioc.definition;

import cn.jnetty.api.annotation.JBean;
import cn.jnetty.api.annotation.JConfiguration;
import cn.jnetty.api.annotation.JPostConstruct;
import cn.jnetty.api.exception.JnettyIocException;
import cn.jnetty.ioc.configruation.JnettyConfiguration;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/4/3 17:44
 * 描述：
 */
public class JConfigurationBeanDefinition extends JDefaultBeanDefinition {
    public JConfigurationBeanDefinition(JConfiguration component, Class<?> clazz) {
        super(component,clazz);
        init();
    }

    @Override
    protected void init() {
        JConfiguration configuration = (JConfiguration) annotation;
        if (configuration == null) {
            return;
        }
        try {
            Object o = clazz.newInstance();
            JDefaultBeanDefinitionFactory.getInstance().put(null,clazz, o);
            jbean(o);
            jpostConstruct(o);
            String[] vale = configuration.value();
            JnettyConfiguration.loading(vale);
        } catch (Exception e) {
            throw new JnettyIocException("创建bena异常{0}",e,clazz.getName());
        }
    }

    private void jbean(Object o) {
        Method[] methods = o.getClass().getMethods();
        for (Method method : methods) {
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                Class<? extends Annotation> annotationType = annotation.annotationType();
                if (annotationType == JBean.class) {
                    JBean scan = JBean.class.cast(annotation);
                    new JBeanDefinition(scan, method, o);
                }
                //其他的生命周期方法
            }
        }
    }
    private void jpostConstruct(Object o){
        Method[] methods = o.getClass().getMethods();
        for (Method method : methods) {
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                Class<? extends Annotation> annotationType = annotation.annotationType();
                if (annotationType == JPostConstruct.class) {
                    JPostConstruct scan = JPostConstruct.class.cast(annotation);
                    new JPostConstructBeanDefinition(scan, method, o);
                }
                //其他的生命周期方法
            }
        }
    }
}